def performace_statistics_delegate(func):
    def counter(*args, **kwargs):
        start = time.clock()
        res = func(*args, **kwargs)
        print('in counter')
        end = time.clock()
        print('[Method : %s,Used time :  %f ]' % (func.__name__, end - start))
        return res

    return counter


# @performace_statistics_delegate
def dosom(name):
    print('in dosom')
    print(name)
    # time.sleep(4)
    print('sleep end')
    print('leave dosom')
    return 'dosom...' + name

# @注解的原理：
dosom = performace_statistics_delegate(dosom)
res = dosom('test')
print(res)

# setTimeout wrapper
import threading
import time


class FunctionWrapper(object):
    def __init__(self, func, *args, **kwargs):
        self.env = {'func': func, 'args': args, 'kwargs': kwargs}
        self.result = []

    def execute(self):
        print(self.env)
        exec("result = func(*args,**kwargs)", self.env)
        self.result.append(self.env['result'])


def settimeout(timeout):
    def checker(func):
        def docheck(*args, **kwargs):
            print(args, kwargs)
            wrapedfunc = FunctionWrapper(func, *args, **kwargs)
            sub_thread = threading.Thread(target=wrapedfunc.execute)
            sub_thread.setDaemon(True)
            sub_thread.start()
            sub_thread.join(timeout)
            if 'result' not in wrapedfunc.env:
                raise Exception('TimeoutError')
            return wrapedfunc.env['result']

        return docheck

    return checker
